package com.demohomework.homeworkdemo.util;

import com.demohomework.homeworkdemo.pojo.AssAllocation;
import com.demohomework.homeworkdemo.pojo.AssSubmit;
import com.demohomework.homeworkdemo.pojo.Student;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

public class RandomUtil {

    /**
     * 随机分配批改任务。
     *
     * @param students            所有参与批改的学生列表
     * @param assignments         所有需要被批改的作业列表
     * @param reviewCountPerStudent 每个学生需要批改的作业数量
     * @param reviewersPerAssignment 每份作业需要被多少个不同的人批改
     * @return 返回一个包含所有分配信息的列表
     */
    public static List<AssAllocation> distributeReviews(List<Student> students, List<AssSubmit> assignments,
                                                        int reviewCountPerStudent, int reviewersPerAssignment) {
        if (students == null || assignments == null || students.isEmpty() || assignments.isEmpty()) {
            throw new IllegalArgumentException("Students or assignments list cannot be null or empty.");
        }

        // Mapping of student ID to a set of assignment IDs they have been assigned to review
        Map<Integer, Set<Integer>> assignedReviews = new HashMap<>();
        for (Student student : students) {
            assignedReviews.put(student.getId(), new HashSet<>());
        }

        List<AssAllocation> allAssAllocations = new ArrayList<>();

        for (AssSubmit assignment : assignments) {
            Set<Integer> reviewers = new HashSet<>();
            while (reviewers.size() < reviewersPerAssignment) {
                Student reviewer = getRandomReviewer(students, assignment.getStuId(), reviewCountPerStudent, assignedReviews);
                reviewers.add(reviewer.getId());

                assignedReviews.get(reviewer.getId()).add(assignment.getId());

                AssAllocation AssAllocation = new AssAllocation();
                AssAllocation.setStuId(reviewer.getId());
                AssAllocation.setAssId(assignment.getId());
                allAssAllocations.add(AssAllocation);
            }
        }
        return allAssAllocations;
    }

    private static Student getRandomReviewer(List<Student> students, int ownerId, int maxReviews, Map<Integer, Set<Integer>> assignedReviews) {
        List<Student> eligibleStudents = students.stream()
                .filter(s -> s.getId() != ownerId)
                .filter(s -> assignedReviews.get(s.getId()).size() < maxReviews)
                .collect(Collectors.toList());

        if (eligibleStudents.isEmpty()) {
            throw new IllegalStateException("Cannot find enough reviewers for the assignment.");
        }

        return eligibleStudents.get(ThreadLocalRandom.current().nextInt(eligibleStudents.size()));
    }
}